<template>
  <div id="detail">
		<detail-nav-bar @titleClick="titleClick" ref="nav"></detail-nav-bar>
    <scroll class="content" ref="scroll" @iscroll="contentScroll" :probe-type="3">
      <!-- 轮播 -->
      <detail-swiper :top-images="topImages" class="detailswiper"></detail-swiper>
      <!-- 商品价格介绍 -->
      <detail-base-info :goods="goods"></detail-base-info>
      <!-- 商家信息总销量和物品描述 -->
      <detail-shop-info :shops="shops"></detail-shop-info>
      <!-- 商品介绍和商品图片 -->
      <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad"></detail-goods-info>
      <!-- 尺码数 -->
      <detail-params-info :goods-params="goodsParams" ref="params"></detail-params-info>
      <!-- 用户评论 -->
      <detail-user-content :user-contents="usercomment" ref="comment"></detail-user-content>
      <!-- 推荐 -->
      <goods-list :goods="recommends" ref="recommend"></goods-list>
      
    </scroll>
    <detail-bottom-bar @addCart="addtocart"></detail-bottom-bar>
    <back-top @click.native="backclick" v-show="isbacktop"/>
	</div>
</template>

<script>
  //这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
  //例如：import 《组件名称》 from '《组件路径》';
	import DetailNavBar from './childComps/DetailNavBar.vue';
	import DetailSwiper from './childComps/DetailSwiper.vue';
	import DetailBaseInfo from './childComps/DetailBaseInfo.vue';
  import DetailShopInfo from './childComps/DetailShopInfo.vue';
  import DetailGoodsInfo from './childComps/DetailGoodsInfo.vue'
  import DetailParamsInfo from './childComps/DetailParamsinfo.vue';
  import DetailUserContent from './childComps/DetailUserContent.vue';
  import GoodsList from '../../components/content/goods/GoodsList.vue';
  import DetailBottomBar from './childComps/DetailBottomBar.vue';

	import {getDetail, getRecommend, Goods, Shop, GoodParams, Ratecontent} from '../../network/detail';
  import Scroll from '../../components/common/scroll/Scroll.vue';

  import {itemListenerMixin, backTopMixin} from '../../common/mimin.js';
  import {debounce} from '../../common/utils.js';
  import {mapActions} from 'vuex';
 
  export default {
    name: 'Detail',
    components: {
			DetailNavBar,
			DetailSwiper,
			DetailBaseInfo,
      DetailShopInfo,
      DetailGoodsInfo,
      DetailParamsInfo,
      DetailUserContent,
      GoodsList,
      DetailBottomBar,
      Scroll,
		},
    props: {},
    mixins:[itemListenerMixin,backTopMixin],
    data() {
    //这里存放数据
      return {
				iid:null,
				topImages:[],
				goods: {},
        shops: {},
        detailInfo:{},
        goodsParams:{},
        usercomment:{},
        recommends:[],
        themeTopYs: [],
        getThemeTopYs: null,
        currentIndex:0,
        
      };
    },
    //计算属性 类似于data概念
    computed: {},
    //监控data中的数据变化
    watch: {},
    //方法集合
    methods: {
      ...mapActions(['addCart']),
      imageLoad(){
        this.$refs.scroll.refresh();
        this.getThemeTopYs();
      },
      titleClick(index){
        // console.log(index);
        this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 100);
      },
      contentScroll(postion){
        //1.判断BackTop是否显示
        this.showBackTop(postion)
       
        // console.log(postion.y);
        //获取Y值
        const postionY = -postion.y;
        //postionY和主题中的值进行对比
        let length =this.themeTopYs.length;
        for(let i=0; i < length;i++){
          // console.log(i,length);
          if (this.currentIndex !== i && ((i< length-1 && postionY >= this.themeTopYs[i] && postionY < this.themeTopYs[i+1]) 
          || (i === length-1 && postionY >= this.themeTopYs[i]))) {
            this.currentIndex = i;
            // console.log(this.currentIndex);
            this.$refs.nav.currentIndex = this.currentIndex;
          }
        }
      },
      addtocart(){
        //a.获取加入购物车相关信息
        const product = {};
        product.image = this.topImages[0];
        product.title = this.goods.title;
        product.desc = this.goods.desc;
        product.price = this.goods.realPrice;
        product.iid = this.iid;
        //b.传入到vuex中
        //提升操作信息
        this.addCart(product).then(res => {
          // console.log(res);
          this.$toast.show(res, 1500)
        })
        // this.$store.dispatch('addCart',product).then(res => {
        //   console.log(res);
        // });
      }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
			//1.保存传入的iid
			this.iid=this.$route.params.iid;

			//2.根据iid请求详情页数据
			getDetail(this.iid).then(res =>{
				// console.log(res);
				const data = res.data.result;
        //a.获取顶部轮播的数据
				this.topImages = data.itemInfo.topImages;
        //b.获取商品信息
				this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services);
        //c.获取商家信息
        this.shops = new Shop(data.shopInfo);
        //d.获取商家详情信息
        this.detailInfo=data.detailInfo;
        //e.获取商家参数信息
        this.goodsParams=new GoodParams(data.itemParams.info, data.itemParams.rule);
        //f.获取用户评论信息
        this.usercomment=new Ratecontent(data.rate)

        /*//第一次获取：值不对。
        //原因是this.$refs.params.$el根本就没有渲染
        this.themeTopYs=[];
        this.themeTopYs.push(0);
        this.themeTopYs.push(this.$refs.params.$el.offsetTop);
        this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
        this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
        console.log(this.themeTopYs);

        this.$nextTick(()=>{
          //第二次获取：值不对。
          //原因是图片没有计算在内
          this.themeTopYs=[];
          this.themeTopYs.push(0);
          this.themeTopYs.push(this.$refs.params.$el.offsetTop);
          this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
          this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
          console.log(this.themeTopYs);
        })*/
			})

      //3.请求推荐数据
      getRecommend().then(res =>{
        // console.log(res);
        this.recommends = res.data.data.list;
      })

      this.getThemeTopYs = debounce(()=>{
        this.themeTopYs=[];
        this.themeTopYs.push(0);
        this.themeTopYs.push(this.$refs.params.$el.offsetTop);
        this.themeTopYs.push(this.$refs.comment.$el.offsetTop || 0);
        this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
        // console.log(this.themeTopYs);
      })
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {},
    beforeCreate() {}, //生命周期 - 创建之前
    beforeMount() {}, //生命周期 - 挂载之前
    beforeUpdate() {}, //生命周期 - 更新之前
    updated() {}, //生命周期 - 更新之后
    beforeDestroy() {}, //生命周期 - 销毁之前
    destroyed() {
      this.$bus.$off('itemImageLoad',this.itemImgListenner);
    }, //生命周期 - 销毁完成
    activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  }
</script>
<style scoped>
#detail{
    position: relative;
    z-index: 11;
    background-color: #fff;
    height: 100vh;
}
.content{
    height: calc(100% - 2.75rem - 3.0625rem);
}
</style>